package com.example.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 描述  阿里云对象存储
 *
 * @author gx
 * @date 2022/1/7 10:17:10
 * @version 1.0
 * @推到云服务
 *  FileInputStream fis = new FileInputStream("/tmp/buildNewImgFile/buildNewImg.jpg");
 * @return：存在对象存储的url     (文件名+后缀,流)
 *  String resultOssUrl = OSSComponent.postObject(UUIDUtil.getUUID()+".jpg", fis);
 * @取数据
 *  InputStream inputStream = cosComponent.getObject(item.getUrl());
 *
 */
@Component
public class OSSComponent {

    @Value("${oss.config.endpoint}")
    private String endpoint;
    @Value("${oss.config.accesskey_id}")
    private String accessKeyId;
    @Value("${oss.config.accesskey_secret}")
    private String accessKeySecret;
    @Value("${oss.config.bucket_name}")
    private String bucketName;

    /**
     * 从OSS服务中下载所需文件到本地临时文件
     *
     * @param basePath 本地临时文件夹
     * @param fileUrls 要下载的对象/文件，在OSS上的URL地址
     * @return
     */
    public void getObjects(String basePath, List<String> fileUrls, List<String> fileNames) {
        if (YHUtil.collectionsIsEmpty(fileUrls) || YHUtil.collectionsIsEmpty(fileNames)) {
            return;
        }
        OSSClient ossClient = null;
        try {
            //创建OSSClient实例，用于操作oss空间
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            for (int i = 0; i < fileUrls.size() && i < fileNames.size(); i++) {
                String fileUrl = fileUrls.get(i);
                if (!isOSSFile(fileUrl)) {
                    continue;
                }
                String fileName = fileNames.get(i);
                //指定文件保存路径
                String filePath = basePath;
                //判断文件目录是否存在，不存在则创建
                File file = new File(filePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                //判断保存文件名是否加后缀
//                if (!fileUrl.contains(".")){
//                    continue;
//                }
                //指定文件保存名称
                filePath = filePath + "/" + fileName;
                // 使用签名URL发送请求。
                Map<String, String> customHeaders = new HashMap<String, String>();
                URL url = new URL(fileUrl);
                ossClient.getObject(new GetObjectRequest(url, customHeaders), new File(filePath));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            //关闭oss连接
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
//        return basePath;
    }
    /*
     * 描述  判断是腾讯云(cos)还是阿里云(oss)
     *
     * @param sourceUrl
     * @return boolean
     * @author gx
     * @date 2022/1/7 10:25:39
     * @version 1.0
     */
    private boolean isOSSFile(String key) {
        if (key.startsWith("http")) {
            try {
                URL url = new URL(key);
                if (!url.getHost().contains("aliyuncs.com")) {
                    return false;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public InputStream getObject(String ossUrl) throws IOException {
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            String url = "oss-cn-hangzhou.aliyuncs.com";
            if (ossUrl.contains(url)) {
                ossUrl = ossUrl.substring(ossUrl.indexOf(url) + url.length() + 1);
            }

//            log.info("ossClient=" + ossClient);
            ossUrl = URLDecoder.decode(ossUrl, "utf-8");
            OSSObject ossObject = ossClient.getObject(bucketName, ossUrl);

            System.out.println("Object content:");

            InputStream objectContent = ossObject.getObjectContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = objectContent.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            return new ByteArrayInputStream(baos.toByteArray());
        } catch (Exception e) {
//            log.error(null, e);
            throw e;
        } finally {
            ossClient.shutdown();
        }
    }
}
